-- 运行另一服务器上的Lua代码

local M = {}

local log = require("log"):new("remote_runner")
local pb = require("protobuf")

-- on_result(result) 生成 rpc 回调函数 cb(resp_str)
local function get_cb(on_result)
	if (not on_result) then return nil end
	assert("function" == type(on_result))

	local cb = function(resp_str)
		assert("string" == type(resp_str))
		local resp = pb.decode("svr.RunLuaResponse", resp_str)
		local codes = resp.codes
		log:debug("RunLuaResponse codes: %q", codes)
		local result = assert(load(codes))()
		on_result(result) -- 回调时执行
	end  -- cb

	return cb
end  -- get_cb()

function M.run(svr_id, codes, on_result)
	assert("number" == type(svr_id))
	assert("string" == type(codes))
	assert(nil == on_result or "function" == type(on_result))
	if (0 == svr_id) then return end
	log:debug("Request Svr_%s to run: %s", svr_id, codes)
	local req = { codes = codes }
	local req_str = pb.encode("svr.RunLuaRequest", req)
	local cb = get_cb(on_result)
	c_rpc.request_svr(svr_id, "svr.RunLua", "Run", req_str, cb)
end  -- run()

return M
